﻿using System;
using System.Text;

using mfLogger;

using mfRCF.Core;
using mfRCF.Core.Extensions;

using mfXmlSerializer;
using mfLogger.NetworkAppenders.Rss;

namespace mfLogger.NetworkAppenders
{
    public class mfRssAppender : mfRcfCommand, ILoggerAppender, IDisposable
    {
        #region CTOR

        public mfRssAppender(string httpPath)
            : base(httpPath, new mfGETMethod())
        {
            Name = GetType().Name;
            IsEnabled = true;
            Level = mfLogger.Instance.Level;

            mfRcf.Instance.Commands.Add(this);
        }

        #endregion

        #region ILoggerAppender

        public bool IsEnabled
        {
            get;
            set;
        }

        public enumLogMessageLevel Level
        {
            get;
            set;
        }

        public void Log(mfLogMessage msg)
        {
            HandleMessage(msg);
        }

        public void Debug(string text)
        {
            HandleMessage(new mfLogMessage(enumLogMessageLevel.Debug, text));
        }

        public void Info(string text)
        {
            HandleMessage(new mfLogMessage(text));
        }

        public void Warning(string text)
        {
            HandleMessage(new mfLogMessage(enumLogMessageLevel.Warning, text));
        }

        public void Error(Exception ex)
        {
            HandleMessage(new mfLogMessage(ex));
        }

        public void Error(string text)
        {
            HandleMessage(new mfLogMessage(enumLogMessageLevel.Error, text));
        }

        public void HandleMessage(mfLogMessage msg)
        {
            if (msg.Level >= Level)
            {
                //TODO: do rss specific stuff here...
            }
        }
        #endregion

        #region mfRcfCommand
        public override void ExecuteCommand(mfIHttpContext httpContext)
        {
            if (!IsEnabled)
            {
                throw new mfRcfException(Name + " is not enabled");
            }

            //convert mfLogger.Instance.Messages 2 rss object
            var filledRSS = BuildRssObject();

            //convert mfLogger.Instance.Messages 2 rss object
            var rssSerializer = new mfXmlTypedSerializer(filledRSS.GetType());

            //hang in rssVersionWriterAction in serialzation-process
            rssSerializer.ElementSerialized += mfWriteRSSVersionAction.WriteRSSVersionAction;

            //serialze xml
            var xmlStream = rssSerializer.SerializeAsStream(filledRSS);
            filledRSS = null;
            rssSerializer.Dispose();
            Microsoft.SPOT.Debug.GC(true);

            //write response
            httpContext.Response.ContentType = ContentTypeOut;
            httpContext.Response.StatusCode = enumHttpStatusCode.OK;
            httpContext.Response.WriteStream(xmlStream);
            httpContext.Response.Close();

            Microsoft.SPOT.Debug.Print(GetType() + " executed, " + Microsoft.SPOT.Debug.GC(true) + " bytes free");
        }

        private rss BuildRssObject()
        {
            var filledRSS = new rss();
            filledRSS.channel.Add(new Channel() { title = mfLogger.Instance.Name + " - Feed", pubDate = DateTime.Now });
            var channel = filledRSS.channel[0];

            for (int i = mfLogger.Instance.Messages.Count-1; i >= 0; i--)
            {
                var msg = mfLogger.Instance.Messages[i];
                var item = new Item()
                {
                    pubDate = msg.TimeStamp
                    ,
                    title = "(" + mfLogMessage.TranslateEndSensorType(msg.Level) + ") " + msg.Text
                };
                channel.item.Add(item);
            }
            return filledRSS;
        }
        #endregion

        public void Dispose()
        {
            mfRcf.Instance.Commands.Remove(this);
        }
    }
}
